package com.aricwang.easyprofile.profile;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.aricwang.easyprofile.R;
import com.aricwang.easyprofile.contentprovider.ProfileContentProvider;
import com.aricwang.easyprofile.database.ProfileTable;
import com.aricwang.easyprofile.service.ProfileService;

/*
 * A ListActivity subclass to list all the profiles.
 */
public class ProfileListActivity extends ListActivity {
	public static final int REQ_ADD_PROFILE  = 1;
	public static final int REQ_EDIT_PROFILE = 2;
	public static final int REQ_COPY_PROFILE = 3;
	
	public static final int DIALOG_WARNING = 1;
	public static final int DIALOG_ADD_PROFILE = 2;
	public static final int DIALOG_PROFILE_LONG_CLICK = 3;
	
	private int mMode = 0;
	private int mCurrentProfile = 0;
	private CursorAdapter mAdapter;
	
	// used to pass information to dialog
	private int mProfileId = 0;
	
	/////////////////////////////////////////////////////////////////////////////////////////
	// Static functions
	/////////////////////////////////////////////////////////////////////////////////////////


	
	/////////////////////////////////////////////////////////////////////////////////////////
	// Public functions
	/////////////////////////////////////////////////////////////////////////////////////////

	// check if a profileId is the current profile applied to the system
	public boolean isCurrentItem(int value) {
		return (value == mCurrentProfile);
	}
	
	/////////////////////////////////////////////////////////////////////////////////////////
	// Override functions
	/////////////////////////////////////////////////////////////////////////////////////////

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// set the layout
		setContentView(R.layout.list);

		// set the onClick handler of the 'add' button
		Button addButton = (Button)findViewById(R.id.btn_add);
		addButton.setOnClickListener(new AddProfileOnClickListener());
		addButton.setText(getText(R.string.new_profile));
		
		// set the onItemLongClick handler of the ListView
		ListView listView = getListView();
		listView.setOnItemLongClickListener(new OnItemLongClickListener());

		// get the list of profile from content provider
		String[] projection = { ProfileTable.COLUMN_ID, ProfileTable.COLUMN_NAME };
		Cursor cursor = getContentResolver().query(ProfileContentProvider.CONTENT_URI, 
				projection, null, null, null);
		startManagingCursor(cursor);
		
		// create the cursor adapter
		String[] columns = new String[] { ProfileTable.COLUMN_ID, ProfileTable.COLUMN_NAME };
		int to[] = new int[] { R.id.list_id, R.id.list_label };
		mAdapter = new CursorAdapter(this, R.layout.profile_list_row, cursor, columns, to);
		
		// finally, set the ListAdapter
		setListAdapter(mAdapter);
		
		// register the profile broadcast receiver.
		IntentFilter filter = new IntentFilter();
		filter.addAction(ProfileService.PROFILE_BROADCAST);
		registerReceiver(new ProfileBroadcastReceiver(), filter);

	}
	
	protected Dialog onCreateDialog(int id) {
	    Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    switch(id) {
	    case DIALOG_WARNING:
            builder.setMessage(R.string.warning_profile_name_empty)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	dialog.dismiss();
                    }
                });
            dialog = builder.create();
	    	break;
	    	
	    case DIALOG_ADD_PROFILE:
	    	LayoutInflater factory = LayoutInflater.from(this);
            final View textEntryView = factory.inflate(R.layout.dialog_edit_text, null);
            
            builder.setTitle(R.string.new_profile)
                .setView(textEntryView)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	// use textEntryView to find the EditText????
                        EditText editText = (EditText)textEntryView.findViewById(R.id.edit_text);
                    	String name = editText.getText().toString();
                    	dialog.dismiss();
                    	
                    	// if name is empty, warn user
                    	if (name.length() <= 0) {
                    		ProfileListActivity.this.showDialog(ProfileListActivity.DIALOG_WARNING);
                    	} else {
	            			// start the ProfileActivity
							ProfileActivity.startActivity(ProfileListActivity.this, REQ_ADD_PROFILE, 0, name);
                    	}
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked cancel so do some stuff */
                    	dialog.cancel();
                    }
                });
            dialog = builder.create();	
	        break;
	        
	    case DIALOG_PROFILE_LONG_CLICK:
	    	final String[] items = { getString(R.string.edit), getString(R.string.delete), getString(R.string.copy),
	    			getString(R.string.force_profile), getString(R.string.unforce_profile)};
	    	final ProfileListActivity activity = (ProfileListActivity)this;
	    	
	    	builder.setTitle(R.string.please_select)
	    		.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String action = items[which];
						dialog.dismiss();

//						Toast.makeText(getApplicationContext(), action + " " + activity.mProfileId, Toast.LENGTH_SHORT ).show();

						if (action == getString(R.string.edit)) {
	            			// start the ProfileActivity
							ProfileActivity.startActivity(activity, REQ_EDIT_PROFILE, activity.mProfileId, null);
						} else if (action == getString(R.string.copy)) {
	            			// start the ProfileActivity
							ProfileActivity.startActivity(activity, REQ_COPY_PROFILE, activity.mProfileId, null);
						} else if (action == getString(R.string.delete)) {
							Profile.deleteProfile(activity, activity.mProfileId);
						} else if (action == getString(R.string.force_profile)) {
							ProfileService.forceProfile(activity, activity.mProfileId);
						} else if (action == getString(R.string.unforce_profile)) {
							ProfileService.unforceProfile(activity, activity.mProfileId);
						}
					}
				});
	    	dialog = builder.create();
	    	break;
	    	
	    default:
	    	break;
	    }
	    
	    return dialog;
	}
	
	protected void onPrepareDialog(int id, Dialog dialog) {
	    switch(id) {
	    case DIALOG_ADD_PROFILE:
            EditText editText = (EditText)dialog.findViewById(R.id.edit_text);
            editText.setText("");
	    	break;
	    default:
	    	break;
	    }
	}
	
	// handle sub-activity result
	protected void onActivityResult (int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK)
			return;
		
		mAdapter.notifyDataSetChanged();
		getListView().smoothScrollToPosition(mAdapter.getCount());
	}

	protected void onListItemClick(ListView l, View v, int position, long id) {
		if (mMode == ProfileService.MODE_AUTO 
				|| (mMode == ProfileService.MODE_MANUAL && mCurrentProfile != id))
		{
			ProfileService.applyProfile(this, (int)id);		
		} else if (mMode == ProfileService.MODE_MANUAL && mCurrentProfile == id) {
			ProfileService.unapplyProfile(this, (int)id);
		}
	}
	
	/////////////////////////////////////////////////////////////////////////////////////////
	// Private functions
	/////////////////////////////////////////////////////////////////////////////////////////
	
	
	/////////////////////////////////////////////////////////////////////////////////////////
	// Inner Classes
	/////////////////////////////////////////////////////////////////////////////////////////

	// 'add' button onClick listener
	private class AddProfileOnClickListener implements View.OnClickListener {
		public void onClick(View v) {
			ProfileListActivity activity = (ProfileListActivity)v.getContext();

			activity.showDialog(ProfileListActivity.DIALOG_ADD_PROFILE);
		}
	}
	
	// item long click event handler
	private class OnItemLongClickListener implements ListView.OnItemLongClickListener {
		public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
			ProfileListActivity activity = (ProfileListActivity)view.getContext();

			// id is the profileId in database, save it to activity
			activity.mProfileId = (int)id;

			activity.showDialog(ProfileListActivity.DIALOG_PROFILE_LONG_CLICK);
			
			// database may changed, update the adapter
			CursorAdapter adapter = (CursorAdapter)parent.getAdapter();
			adapter.notifyDataSetChanged();

			// Return true to consume the click event. In this case the
			// onListItemClick listener is not called anymore.
			return true;
		}
	}
	
	/*
	 * A SimpleCursorAdapter subclass to manage the customized ListView for ProfileListActivity
	 */
	private class CursorAdapter extends SimpleCursorAdapter {
		private ProfileListActivity mActivity;
		private Cursor  mCursor;
		
		public CursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
			super(context, layout, c, from, to);
			
			mActivity = (ProfileListActivity)context;
			mCursor = c;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			mCursor.moveToPosition(position);
			int id = mCursor.getInt(0);
			String name = mCursor.getString(1);
			
			View rowView;
			
			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater)mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				rowView = inflater.inflate(R.layout.profile_list_row, parent, false);	
			} else {
				rowView = convertView;
			}
			
			TextView idView = (TextView) rowView.findViewById(R.id.list_id);
			TextView nameView = (TextView) rowView.findViewById(R.id.list_label);
			ImageView imgView = (ImageView)rowView.findViewById(R.id.list_check);

			idView.setText(Integer.toString(id));
			nameView.setText(name);
			
			if (mActivity.mCurrentProfile == id) {
				if (mActivity.mMode == ProfileService.MODE_FORCED)
					imgView.setImageResource(android.R.drawable.btn_star_big_on);
				else if (mActivity.mMode == ProfileService.MODE_MANUAL)
					imgView.setImageResource(android.R.drawable.btn_star_big_off);
				else if (mActivity.mMode == ProfileService.MODE_AUTO)
					imgView.setImageResource(android.R.drawable.checkbox_on_background);
				else 
					imgView.setImageResource(0);
			} else {
				imgView.setImageResource(0);
			}

			return rowView;
		}
		
	}
	
	public class ProfileBroadcastReceiver extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) { 
			String action = intent.getAction();
			if (action.equals(ProfileService.PROFILE_BROADCAST)) {
				int mode = intent.getExtras().getInt("Mode");
				int profileId = intent.getExtras().getInt("ProfileId");
//				String name = intent.getExtras().getString("ProfileName");
//				Log.i("T", "profile broadcast received: mode " + mode + " profileId " + profileId + " name " + name);
				
				ProfileListActivity.this.mMode = mode;
				ProfileListActivity.this.mCurrentProfile = profileId;
				ProfileListActivity.this.mAdapter.notifyDataSetChanged();
			}
		} 
	}

}
